<template>
  <div class="header-container">
    <nav-bar
      :title="'订单详情'"
      :showLeftArrow="true"
      :leftText="'返回'"
      @click-left="back"
    >
    </nav-bar>
  </div>
  <div class="main-container">
    <div class="order-status">
      <div class="status-item">
        <label>订单状态：</label>
        <span>
          <van-tag v-if="order.orderStatus == orderStatus.UNPAID" color="cyan">
            待付款
          </van-tag>
          <van-tag
            v-if="order.orderStatus == orderStatus.UN_EXPRESSED"
            color="blue"
          >
            待发货
          </van-tag>
          <van-tag
            v-if="order.orderStatus == orderStatus.EXPRESSED"
            color="pink"
          >
            待收货
          </van-tag>
          <van-tag
            v-if="order.orderStatus == orderStatus.RECEIVED"
            color="purple"
          >
            已收货
          </van-tag>
          <van-tag
            v-if="order.orderStatus == orderStatus.COMPLETE"
            color="green"
          >
            已完成
          </van-tag>
          <van-tag v-if="order.orderStatus == orderStatus.CLOSED" color="red">
            已关闭
          </van-tag>
        </span>
      </div>
      <div class="status-item">
        <label>订单编号：</label>
        <span>{{ order.code }}</span>
      </div>
      <div class="status-item">
        <label>下单时间：</label>
        <span>{{ order.orderTime }}</span>
      </div>
      <van-button
        v-if="order.orderStatus == orderStatus.EXPRESSED"
        style="margin-bottom: 10px"
        type="danger"
        block
        @click="handleConfirmOrder(order)"
      >
        确认收货
      </van-button>
      <van-button
        v-if="order.orderStatus == orderStatus.UNPAID"
        style="margin-bottom: 10px"
        type="danger"
        block
        @click="showPayment"
      >
        去支付
      </van-button>
      <van-button
        v-if="
          order.orderStatus == orderStatus.UNPAID ||
          order.orderStatus == orderStatus.UN_EXPRESSED
        "
        block
        @click="handleCancelOrder"
      >
        取消订单
      </van-button>
    </div>
    <div class="order-price">
      <div class="price-item">
        <label>商品金额：</label>
        <span>¥ {{ order.amount }}</span>
      </div>
      <div class="price-item">
        <label>配送方式：</label>
        <span>普通快递</span>
      </div>
    </div>
    <van-card
      v-for="item in order.items"
      :key="item.id"
      :title="item.productName"
      :price="item.price"
      :thumb="item.productImgUrl"
      :num="item.quantity"
    />
  </div>
  <van-popup
    closeable
    :close-on-click-overlay="false"
    v-model:show="paymentShown"
    position="bottom"
    :style="{ height: '30%' }"
    @close="closePay"
  >
    <div :style="{ width: '90%', margin: '0 auto', padding: '50px 0' }">
      <van-button
        :style="{ marginBottom: '10px' }"
        color="#1989fa"
        block
        @click="handlePayOrder(paymentType.ALI_PAY)"
      >
        支付宝支付
      </van-button>
      <van-button
        color="#4fc08d"
        block
        @click="handlePayOrder(paymentType.WECHAT)"
      >
        微信支付
      </van-button>
    </div>
  </van-popup>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import NavBar from "@/components/NavBar.vue";
import { Dialog, Toast } from "vant";
import { AxiosError } from "axios";
import orderService from "@/services/order.service";
import OmsOrder from "@/entity/OmsOrder";
import PaymentType from "@/entity/OmsPaymentType";
import OrderStatus from "@/entity/OmsOrderStatus";
import OmsOrderUpdateParam from "@/entity/OmsOrderUpdateParam";

type StateType = {
  id?: number | null;
  order?: OmsOrder | null;
  paymentShown: boolean;
};
export default defineComponent({
  components: {
    NavBar,
  },
  setup() {
    const paymentType = PaymentType;
    const orderStatus = OrderStatus;
    const route = useRoute();
    const router = useRouter();
    const state = reactive<StateType>({
      id: undefined,
      order: new OmsOrder(),
      paymentShown: false,
    });

    onMounted(async () => {
      if (route.query.id != null) {
        state.id = Number(route.query.id);
      }
      await load();
    });

    const load = async () => {
      try {
        if (state.id != null) {
          const order = await orderService.retrieve(state.id);
          state.order = order;
        }
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const back = () => {
      router.push("/order");
    };

    const showPayment = () => {
      state.paymentShown = true;
    };

    const handlePayOrder = async (paymentType: PaymentType) => {
      try {
        const param: OmsOrderUpdateParam = {
          id: state.id || -1,
          orderStatus: OrderStatus.UN_EXPRESSED,
        };
        const id = await orderService.update(param);
        Toast.success("支付成功");
        state.paymentShown = false;
        load();
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const closePay = async () => {
      try {
        state.paymentShown = false;
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const handleConfirmOrder = async () => {
      try {
        Dialog.confirm({
          title: "是否确认订单？",
        })
          .then(async () => {
            const param: OmsOrderUpdateParam = {
              id: state.id || -1,
              orderStatus: OrderStatus.COMPLETE,
            };
            const id = await orderService.update(param);
            load();
          })
          .catch(() => {
            // on cancel
          });
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    const handleCancelOrder = () => {
      try {
        Dialog.confirm({
          title: "确认取消订单？",
        })
          .then(async () => {
            const param: OmsOrderUpdateParam = {
              id: state.id || -1,
              orderStatus: OrderStatus.CLOSED,
            };
            const id = await orderService.update(param);

            load();
          })
          .catch(() => {
            // on cancel
          });
      } catch (e) {
        if (e instanceof AxiosError && e.response?.status == 401) {
          Toast.fail("请先登录");
          router.push("/login");
          return;
        }
        Toast.fail("加载失败");
        throw e;
      } finally {
      }
    };

    return {
      paymentType,
      orderStatus,
      ...toRefs(state),
      back,
      showPayment,
      handlePayOrder,
      closePay,
      handleConfirmOrder,
      handleCancelOrder,
    };
  },
});
</script>

<style scoped>
.order-status {
  background: #fff;
  padding: 10px 20px;
  font-size: 15px;
}
.order-status .status-item {
  margin-bottom: 10px;
}
.order-status .status-item label {
  color: #999;
}
.order-price {
  background: #fff;
  /* margin: 20px 0; */
  padding: 10px 20px;
  font-size: 15px;
}
.order-price .price-item {
  margin-bottom: 10px;
}
.order-price .price-item label {
  color: #999;
}
.van-card {
  margin-top: 0;
}
.van-card__content {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.van-card {
  background-color: #fff;
  margin-top: 0;
}
</style>